package it.sciuto.criminal.activities;

import it.sciuto.criminal.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.CharacterIterator;
import java.text.StringCharacterIterator;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.text.format.DateFormat;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class LetterActivity extends Activity {

	private LinearLayout mainLayout;
	private EditText text;
	private ImageButton convertButton;
	private ImageButton saveButton;
	private ImageButton shareButton;
	private ImageButton deleteButton;
	private ImageButton blackButton;
	private ImageButton colorButton;

	private boolean isColor = true;

	private String lastSaved = "";

	private static int randomSize[] = { 22, 28, 30, 34, 32, 26, 20 };
	private static int randomBackColor[] = { R.drawable.green1, R.drawable.green2, R.drawable.green3, R.drawable.green4, R.drawable.black1, R.drawable.black2, R.drawable.black3, R.drawable.black4, R.drawable.orange1, R.drawable.orange2, R.drawable.orange3, R.drawable.orange4, R.drawable.red1,
			R.drawable.red2, R.drawable.red3, R.drawable.red4 };

	private static int randomBackBlack[] = { R.drawable.black1, R.drawable.black2, R.drawable.black3, R.drawable.black4 };

	private String randomFonts[];

	private Random random = new Random();

	private void initFonts() {
		AssetManager assets = getAssets();
		try {
			randomFonts = assets.list("fonts");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private CharSequence setFileName() {
		Date d = new Date();
		return DateFormat.format("ddMMyyyy_hhmmss", d.getTime()) + ".jpg";
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.letter);

		// Fade Animation
		overridePendingTransition(R.anim.fadein, R.anim.fadeout);

		// Init directory
		File f = new File("/mnt/sdcard/criminal/");
		if (!f.exists())
			f.mkdirs();

		// Init fonts
		initFonts();

		mainLayout = (LinearLayout) findViewById(R.id.main_layout);
		mainLayout.setBackgroundResource(R.drawable.copybook);
		text = (EditText) findViewById(R.id.text);
		convertButton = (ImageButton) findViewById(R.id.convert_button);
		convertButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				mainLayout.removeAllViews();
				mainLayout.invalidate();
				LinearLayout row = new LinearLayout(LetterActivity.this);

				CharacterIterator it = new StringCharacterIterator(text.getText().toString());
				for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
					if (ch == '\n' || ch == ' ') {
						mainLayout.addView(row);
						row = new LinearLayout(LetterActivity.this);
						continue;
					}

					TextView i = new TextView(LetterActivity.this);
					if (isColor)
						i.setBackgroundResource(randomBackColor[random.nextInt(randomBackColor.length)]);
					else
						i.setBackgroundResource(randomBackBlack[random.nextInt(randomBackBlack.length)]);

					i.setText("" + ch);
					i.setTextSize(randomSize[random.nextInt(randomSize.length)]);
					i.setTextColor(Color.WHITE);
					i.setGravity(Gravity.CENTER);
					String font = "fonts/" + randomFonts[random.nextInt(randomFonts.length)];

					i.setTypeface(Typeface.createFromAsset(getAssets(), font));
					row.addView(i);
					// if (it.getIndex() % 7 == 6) {
					// mainLayout.addView(row);
					// row = new LinearLayout(CriminalLecterActivity.this);
					// }

				}
				mainLayout.addView(row);
				mainLayout.invalidate();
			}
		});

		deleteButton = (ImageButton) findViewById(R.id.delete_button);
		deleteButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				AlertDialog.Builder builder = new AlertDialog.Builder(LetterActivity.this);
				builder.setMessage(R.string.delete_question).setCancelable(false).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						text.setText("");
						mainLayout.removeAllViews();
						mainLayout.invalidate();
					}
				}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						dialog.cancel();
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
			}
		});

		saveButton = (ImageButton) findViewById(R.id.save_button);
		saveButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				lastSaved = "/sdcard/criminal/" + setFileName();
				saveBitmap(loadBitmapFromView(mainLayout), lastSaved);
			}
		});

		shareButton = (ImageButton) findViewById(R.id.share_button);
		shareButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				saveBitmap(loadBitmapFromView(mainLayout), "/sdcard/criminal/shared.jpg");
				share();
			}
		});

		colorButton = (ImageButton) findViewById(R.id.color_button);
		colorButton.setSelected(isColor);
		colorButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				isColor = true;
				colorButton.setSelected(true);
				blackButton.setSelected(false);
			}
		});

		blackButton = (ImageButton) findViewById(R.id.black_white_button);
		blackButton.setSelected(!isColor);
		blackButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				isColor = false;
				colorButton.setSelected(false);
				blackButton.setSelected(true);
			}
		});

	}

	public void saveBitmap(Bitmap bmp, String filename) {
		try {
			FileOutputStream out = new FileOutputStream(filename);
			bmp.compress(Bitmap.CompressFormat.JPEG, 100, out);
			out.flush();
			out.close();
			bmp.recycle();
			Toast.makeText(this, R.string.save_ok, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
			Toast.makeText(this, R.string.save_error, Toast.LENGTH_LONG).show();
		}

	}

	public void share() {
		Intent share = new Intent(Intent.ACTION_SEND);
		share.setType("image/jpeg");
		share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/criminal/shared.jpg"));
		startActivity(Intent.createChooser(share, getString(R.string.share_title)));
	}

	public Bitmap loadBitmapFromView(View v) {
		v.setDrawingCacheEnabled(true);
		Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
		v.setDrawingCacheEnabled(false);
		return b;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(R.string.papyrus).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.papyrus);
				return true;
			}
		});
		menu.add(R.string.parchment).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.parchment);
				return true;
			}
		});

		menu.add(R.string.wall).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.wall);
				return true;
			}
		});
		menu.add(R.string.copybook).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.copybook);
				return true;
			}
		});
		menu.add(R.string.fingerprint).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.fingerprint);
				return true;
			}
		});
		menu.add(R.string.postit).setOnMenuItemClickListener(new OnMenuItemClickListener() {
			public boolean onMenuItemClick(MenuItem item) {
				mainLayout.setBackgroundResource(R.drawable.postit);
				return true;
			}
		});
		return true;
	}
}